package com.sk.bilibili.service;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sk.bilibili.other.R;
import com.sk.bilibili.utils.BSessionUtils;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.regex.Pattern;

import org.springframework.beans.factory.annotation.Autowired;
import com.sk.bilibili.bean.Pendant;
import com.sk.bilibili.mapper.PendantMapper;

/**
 * @author 邵康
 * @date 2021/12/04 19:21
 */
@Service
public class PendantService extends ServiceImpl<PendantMapper, Pendant> {

    @Autowired
    private MinioService minioService;
    private static final String URL_PATH = "pendant/url/%s.png";
    private static final Pattern URL_PATTERN = Pattern.compile("/(pendant/url/.*png)");

    public R<Void> add(Pendant pendant) {
        pendant.setUrl(minioService.add(pendant.getUrlFile(), URL_PATH));
        save(pendant);
        return R.success();
    }

    public R<Void> delete(Integer id) {
        Pendant temp = getById(id);
        minioService.delete(temp.getUrl(), URL_PATTERN);
        removeById(id);
        return R.success();
    }

    public R<Void> update(Pendant pendant) {
        Pendant temp = getById(pendant.getId());
        String url = minioService.update(URL_PATH, URL_PATTERN, temp.getUrl(), pendant.getUrlFile());
        pendant.setUrl(url);
        updateById(pendant);
        return R.success();
    }

    public R<IPage<Pendant>> page(Integer page, Integer size) {
        return R.success(page(new Page<>(page, size), null));
    }

    public R<List<Pendant>> getAll() {
        List<Pendant> res = baseMapper.getAll(BSessionUtils.getMemberId());
        return R.success(res);
    }

}
